package com.isunimp.sample.java.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * Created by isunimp on 17/2/17.
 */
public class EchoClient {


    public static void main(String[] args) throws FileNotFoundException {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(9999));
            ByteBuffer byteBuffer = ByteBuffer.allocate(100);

//            while (true) {
                int bytesRead = socketChannel.read(byteBuffer);
                if (bytesRead > 0) {
                    byte[] bytes = new byte[bytesRead];
                    byteBuffer.flip();  //make buffer ready for read

//                while (byteBuffer.hasRemaining()) {
//                    System.out.print((char) byteBuffer.get()); // read 1 byte at a time
//                }
                    byteBuffer.get(bytes);
                    System.out.println(new String(bytes));
                }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
